<script setup lang="ts">
import { libraryRequestParams, RequestParams } from "@/api/library/type";
//import SingleUpload from "@/components/Upload/SingleUpload.vue";
import {
  libraryList,
  FormLibrary,
  LibraryOptions,
  updateLibrary,
} from "@/api/library/index";
import { ElMessage } from "element-plus";
import { computed, onMounted, reactive, ref } from "vue";
import useUserStore from "@/store/modules/user";
import dayjs from "dayjs";
let useStore = useUserStore();

// ================================================================================
// ref
const queryFormRef = ref(); //搜索
const ruleFormRef = ref(); //弹框表单

const ids = ref([] as number[]); //表格全选
const total = ref();
const loading = ref(false);
const dialogVisible = ref(false);
const title = ref("新增");
let LibOptions = ref([] as any);
const ruleForm = ref({} as any);
let queryParams = reactive({
  pageNum: 1,
  pageSize: 10,
  libraryName: "",
} as any);
const tableList = ref([{}] as libraryRequestParams[]);

const rules = reactive({
  libraryName: [
    { required: true, message: "图书馆不能为空", trigger: "blur" },
    { min: 1, max: 15, message: "图书馆名称过长", trigger: "blur" },
  ],
  libraryBeginTime: [
    { required: true, message: "开馆时间不能为空", trigger: "change" },
  ],
  libraryEndTime: [
    { required: true, message: "开馆时间不能为空", trigger: "change" },
  ],
  libraryAddress: [
    { required: true, message: "图书馆地址不能为空", trigger: "blur" },
    { min: 1, max: 50, message: "图书馆地址过长", trigger: "blur" },
  ],
  fileI: [
    {
      required: true,
      message: "请选择营业执照",
      trigger: "blur",
    },
  ],
});

// 挂载
onMounted(() => {
  handleQuery();
});
// ================================================================================
/**
 * 枚举
 */
// const getStatusText = (status: any) => {
//   const STATUSES = [
//     { id: "0", name: "预约中" },
//     { id: "1", name: "完成" },
//   ];
//   const matched = STATUSES.find((item) => item.id === status);
//   return matched ? matched.name : "";
// };
/**
 * 查询
 */
const handleQuery = async () => {
  try {
    loading.value = true;
    const res = await libraryList(queryParams);
    //console.log(res, "res");

    // 格式化 libraryBeginTime 字段为 HH:mm:ss
    const formattedRecords = [] as any;
    res.data.records.forEach((record) => {
      if (dayjs(record.libraryBeginTime).isValid()) {
        record.libraryBeginTime = dayjs(record.libraryBeginTime).format(
          "HH:mm:ss"
        );
        record.libraryEndTime = dayjs(record.libraryEndTime).format("HH:mm:ss");
      } else {
        // 如果 libraryBeginTime 为 "Invalid Date"，可以设置一个默认占位值或者跳过设置
        record.libraryBeginTime = ""; // 或者其他占位值
        record.libraryEndTime = ""; // 或者其他占位值
        // 这里选择不做任何操作，即不设置该字段
      }
      formattedRecords.push(record);
    });

    tableList.value = formattedRecords;
    total.value = res.data.total;
    loading.value = false;
  } catch (error) {
    console.error(error);
    loading.value = false;
  }
};

/**
 * 重置
 */
const resetQuery = () => {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  queryParams.libraryName = "";
  queryFormRef.value.clearValidate();
  handleQuery();
};
/**
 * 行checkbox change事件
 */
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}
/**
 * 打开弹框
 */
const openDialog = async (id?: number) => {
  dialogVisible.value = true;
  const res = await LibraryOptions(useStore.encryptedData);
  LibOptions.value = res.data;
  //console.log(LibOptions.value, "LibOptions");

  if (id) {
    const res = await FormLibrary(id as any);
    ruleForm.value = res.data;
    // console.log(res, "addFormUser");
    title.value = "修改开闭馆时间";
  } else {
    title.value = "新增开闭馆时间";
    ruleForm.value = {};
  }
};
/**
 * 关闭弹框
 */
const close = () => {
  dialogVisible.value = false;
  ruleFormRef.value.resetFields();
  ruleFormRef.value.clearValidate();
  ruleForm.value = {} as any;
};
const formatDateTime = () => {
  const formattedDateTime = dayjs(ruleForm.value.libraryBeginTime).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  ruleForm.value.libraryBeginTime = formattedDateTime;
  // console.log(formattedDateTime, "formattedDateTime");
};
const DateTime = () => {
  const formattedDateTime = dayjs(ruleForm.value.libraryEndTime).format(
    "YYYY-MM-DD HH:mm:ss"
  );
  ruleForm.value.libraryEndTime = formattedDateTime;
  // console.log(formattedDateTime, "formattedDateTime");
};
/**
 * 处理表单提交事件
 */
const submit = async () => {
  ruleFormRef.value.validate((valid: any) => {
    if (valid) {
      const userId = ruleForm.value.id;
      loading.value = true;

      if (userId) {
        // console.log(ruleForm.value, "编辑");
        updateLibrary(ruleForm.value)
          .then(() => {
            ElMessage.success("修改成功");
            close();

            handleQuery();
          })
          .finally(() => (loading.value = false));
      } else {
      }
    }
  });
};

const handleSizeChange = (val: number) => {
  queryParams.pageSize = val;
  queryParams.pageNum = 1;

  handleQuery();
};
const handleCurrentChange = (val: number) => {
  queryParams.pageNum = val;
  handleQuery();
  window.scrollTo({ top: 0, behavior: "smooth" }); // 立即回到顶部，并使用平滑滚动效果
};

const indexMethod = (index: any) => {
  // 1、index:代表当前行数据的下标
  // 2、下标+1:  分页不要纠结：这块不是业务，完全是数学问题！
  return index + 1 + (queryParams.pageNum - 1) * queryParams.pageSize;
};
const isSearchDisabled = computed(() => {
  return useStore.user.roles.includes("ADMIN");
});
</script>

<template>
  <div class="app-container">
    <el-dialog
      v-model="dialogVisible"
      :title="title"
      width="600px"
      append-to-body
      @close="close"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="110px"
        status-icon
      >
        <!-- <el-form-item label="营业执照" prop="fileUrl">
          <single-upload v-model="ruleForm.fileUrl" />
        </el-form-item> -->
        <el-form-item label="图书馆" prop="libraryName">
          <el-input
            :disabled="isSearchDisabled"
            style="width: 350px"
            v-model="ruleForm.libraryName"
            placeholder="请输入图书馆名称"
          />
        </el-form-item>
        <el-form-item label="开馆时间" prop="libraryBeginTime">
          <el-time-picker
            v-model="ruleForm.libraryBeginTime"
            placeholder="请选择时间"
            @change="formatDateTime"
          />
        </el-form-item>
        <el-form-item label="闭馆时间" prop="libraryEndTime">
          <el-time-picker
            v-model="ruleForm.libraryEndTime"
            placeholder="请选择时间"
            @change="DateTime"
          />
          <!-- <el-input
            style="width: 350px"
            v-model="ruleForm.libraryEndTime"
            placeholder="请输入闭馆时间"
          /> -->
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submit">确 定</el-button>
          <el-button @click="close">取 消</el-button>
        </div>
      </template>
    </el-dialog>
    <div class="search">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item label="图书馆" prop="name">
          <el-input
            v-model="queryParams.libraryName"
            placeholder="请输入图书馆名称"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery" icon="Search"
            >搜索</el-button
          >
          <el-button @click="resetQuery" icon="Refresh">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <el-card>
      <template #header>
        <!-- <el-button icon="Plus" type="success" @click="openDialog()"
          >新增</el-button
        > -->
        <!-- <el-button type="danger" :disabled="ids.length === 0" icon="Delete"
          >删除</el-button
        > -->
      </template>
      <el-table
        v-loading="loading"
        highlight-current-row
        :data="tableList"
        @selection-change="handleSelectionChange"
      >
        <el-table-column
          type="index"
          width="80"
          label="序号"
          :align="'center'"
          :index="indexMethod"
        />
        <!-- <el-table-column type="selection" width="55" align="center" /> -->
        <el-table-column label="图书馆名称" prop="libraryName" align="center" />
        <!-- <el-table-column
          label="图书馆地址"
          prop="libraryAddress"
          align="center"
        />
        <el-table-column
          label="详细地址"
          prop="libraryFullAddress"
          align="center"
        /> -->
        <!-- <el-table-column
          label="图书馆邮箱"
          prop="libraryEmail"
          align="center"
        /> -->
        <el-table-column
          label="开馆时间"
          prop="libraryBeginTime"
          align="center"
        />
        <el-table-column
          label="闭馆时间"
          prop="libraryEndTime"
          align="center"
        />

        <el-table-column fixed="right" label="操作" align="center" width="220">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              size="small"
              @click="openDialog(row.id)"
              icon="Edit"
              >编辑</el-button
            >
            <!-- <el-button
              type="primary"
              link
              size="small"
              @click="dell(row.id)"
              icon="Delete"
              >删除</el-button
            > -->
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        style="margin-top: 15px"
        v-model:current-page="queryParams.pageNum"
        v-model:page-size="queryParams.pageSize"
        :page-sizes="[10, 20, 30, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </el-card>
  </div>
</template>

<style lang="scss" scoped></style>
